package util;


import io.jsonwebtoken.*;
import org.json.JSONObject;
import org.junit.Test;

import java.util.Date;
public class JwtUtil {
    public static final String subject="九职校园论坛";
    public static final String key="111111";
//    为负数时token不过期
    public static final long ttlMillis=-1;
//    @Test
//    public void test(){
//        String token=createJWT(7932,"九职校园论坛","11111",500000000);
//        System.out.println(token);
//        System.out.println(parseJWT(token));
//        System.out.println(parseJWT(token).getId());
//        System.out.println(validateJWT(token));
//    }
    public String createJWT(int account,String subject,String key,long ttlMillis){
        //获取签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder = Jwts.builder()
                .setId(String.valueOf(account))
                .setSubject(subject)
                .setIssuer("user")
                .setIssuedAt(now)
                .signWith(signatureAlgorithm,key);
        if(ttlMillis >= 0){
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            //设置过期时间
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }

    public static Claims parseJWT(String jwt) {
        return Jwts.parser().setSigningKey("11111").parseClaimsJws(jwt).getBody();
    }

    public static boolean validateJWT(String jwtStr) {
        JSONObject pojo = new JSONObject();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            return true;
        } catch (ExpiredJwtException e) {

            e.printStackTrace();
            return false;
        } catch (Exception e) {

            e.printStackTrace();
            return false;
        }
    }
}
